package com.onepiece.OJ.service.impl;

import com.onepiece.OJ.service.UploadService;
import com.onepiece.OJ.utils.AliyunOSSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;

@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @Override
    public String uploadMD(@RequestParam("file") MultipartFile file) {
        String filename = file.getOriginalFilename();
        String uploadUrl =null;
        try {
            if (file != null) {
                if(!filename.endsWith(".md")) {
                    throw new Exception("请上传md格式的文件");
                }
                if (!"".equals(filename.trim())) {
                    //MultipartFile转换成File
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    // 上传到OSS
                    uploadUrl = aliyunOSSUtil.upLoad(newFile,"articleMD");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return uploadUrl;
    }
    @Override
    public String uploadImg(MultipartFile file) {
        String filename = file.getOriginalFilename();
        String uploadUrl =null;
        try {
            if (file != null) {
                if(!filename.endsWith(".png")&&!filename.endsWith(".jpg")) {
                    throw new Exception("请上传png或jpg格式的文件");
                }
                if (!"".equals(filename.trim())) {
                    //MultipartFile转换成File
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    // 上传到OSS
                    uploadUrl = aliyunOSSUtil.upLoad(newFile,"picture");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return uploadUrl;
    }
}
